import json
from PyQt5.QtWidgets import QMessageBox,QWidget
from PyQt5.QtCore import Qt,QThread,pyqtSignal
from PyQt5 import uic
from PyQt5.QtGui import QIcon,QCursor
from pages.SelectArea import SelectArea
from pages.ControlArea import ControlArea
from system_hotkey import SystemHotkey,SystemRegisterError
import os 
__dir__ = os.path.dirname(os.path.abspath(__file__))
__ui_dir__ = os.path.join(__dir__, '../ui/MainWindow.ui')
__icon_dir__ = os.path.join(__dir__, '../icon')
__config_dir__ = os.path.join(__dir__, '../config.json')

HK_KEY = 'HK_'
LAN = '自汉英日韩'
class MainWindow(QWidget):
    IS_CHILD_HIDE = False   # 是否隐藏选定区域窗口
    IS_TOP = False          # 是否置顶
    IS_AUTO = False         # 是否自动
    control = None          # 识别翻译控制器
    HK_LIST = ['' for i in range(0, 5)] # 热键列表
    hk = SystemHotkey()     # 热键实现对象
    IS_MOVING = False       # 主窗体是否正在移动
    IS_HAVE_AREA = False    # 是否已经选定过区域

    def __init__(self, control):
        super().__init__()
        self.control = control
        self.HK_LIST = [control.config['HK_'+str(i)] for i in range(0, 5)]
        # 使用ui文件导入定义界面类
        uic.loadUi(__ui_dir__, self)
        self.wid = [self.menuSelector_1, self.menuSelector_2, self.menuSelector_3, self.menuSelector_6, self.menuSelector_8]
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 初始化布局
        # 部分控件的鼠标样式
        self.menuSelector_10.setCursor(Qt.OpenHandCursor)
        self.span_0.setCursor(Qt.OpenHandCursor)
        self.span_1.setCursor(Qt.OpenHandCursor)
        # 当前单选框默认选项更变
        self.menuSelector_4.setCurrentIndex(control.config['SOURCE_LANGUAGE'])
        self.chanShowMode(control.config['SHOW_MODE'])
        self.th = CycleThread()
        # 事件绑定
        self.th.timing.connect(self.OnShot)
        self.span_0.pressed.connect(self.OnPressEvent)
        self.span_1.pressed.connect(self.OnPressEvent)
        self.menuSelector_10.pressed.connect(self.OnPressEvent)
        self.menuSelector_9.clicked.connect(self.OnExit)
        self.menuSelector_8.clicked.connect(self.OnTop)
        self.menuSelector_7.clicked.connect(self.OnSet)
        self.menuSelector_6.clicked.connect(self.OnShowMode)
        self.menuSelector_5.clicked.connect(self.OnReadMode)
        self.menuSelector_4.currentIndexChanged.connect(self.OnLanguage)
        self.menuSelector_3.clicked.connect(self.OnHideCon)
        self.menuSelector_2.clicked.connect(self.OnSelectArea)
        self.menuSelector_1.clicked.connect(self.OnShot)
        # 全局热键注册
        self.initHK()
        self.setWindowIcon(QIcon(__icon_dir__+'\yhd.jpg'))

    # 初始化热键
    def initHK(self):
        for i in range(0, 5):
            key = self.HK_LIST[i]
            if  key != '':
                self.dfHK(i, key)

    # 改变热键
    def chanHK(self, i):
        key = self.control.config[HK_KEY+str(i)]
        if key != self.HK_LIST[i]:# 已变化，注销原热键
            try:
                arr = self.HK_LIST[i].split('+')
                if '' not in arr and self.HK_LIST[i]:
                    self.hk.unregister(arr)
            except SystemRegisterError:
                QMessageBox.critical(self, "错误", "快捷键功能发送错误，请重启程序")
            finally:
                self.HK_LIST[i] = key
            self.dfHK(i, key)
        else: # 未变化，无操作
            print('热键未变化')
            pass
        
    # 热键定义函数
    def dfHK(self, i, key):
        arr = key.split('+')
        print(arr)
        if key and ('' not in arr):
            try:
                self.hk.register(arr, callback=lambda x: self.wid[i].click())
            except SystemRegisterError:
                QMessageBox.critical(self, "错误", "快捷键功能发送错误，请重启程序")

    # 截图
    def OnShot(self):
        if self.IS_HAVE_AREA:
            img = self.area.capturePhoto()
            reg = self.area.regPhoto()
            tran = self.area.tranPhoto()
            self.regTextBox.setText(reg)
            self.tranTextBox.setText(tran)
        else:
            QMessageBox.warning(self, "警告", "还没有确定截图区域")

    # 选择矩形区域
    def OnSelectArea(self):
        if self.IS_CHILD_HIDE:
            self.OnHideCon()
        self.showMinimized()
        self.area = ControlArea(self.control)
        self.select = SelectArea(self.area)

    # 隐藏选区边框
    def OnHideCon(self):
        if self.IS_HAVE_AREA:
            if self.IS_CHILD_HIDE:
                self.area.show()
                self.IS_CHILD_HIDE = False
                self.menuSelector_3.setIcon(QIcon(__icon_dir__ + '/show.png'))
            else:
                self.area.hide()
                self.IS_CHILD_HIDE = True
                self.menuSelector_3.setIcon(QIcon(__icon_dir__ + '/hide.png'))
        else:
            QMessageBox.warning(self, "警告", "还没有确定截图区域")
    
    # 更换源语言
    def OnLanguage(self, e):
        # print(e)
        self.control.chanSourceLan(e)

    # 更换截图模式
    def OnReadMode(self):
        if self.IS_AUTO:
            self.IS_AUTO = False
            self.menuSelector_5.setIcon(QIcon(__icon_dir__ + '/hand.png'))
        else:
            if self.IS_HAVE_AREA:
                self.IS_AUTO = True
                self.menuSelector_5.setIcon(QIcon(__icon_dir__ + '/timing.png'))
            else:
                QMessageBox.warning(self, "警告", "还没有确定截图区域")
                self.IS_AUTO = False         
                return
        self.timingReg()

    # 更换下一个显示模式
    def OnShowMode(self):
        # 0 为双显示，1 为只显示感知，2 为只显示翻译
        SHOW_MODE = self.control.config['SHOW_MODE']
        SHOW_MODE = (SHOW_MODE+1) % 3
        self.control.config['SHOW_MODE'] = SHOW_MODE
        self.chanShowMode(SHOW_MODE)
        
    # 打开设置
    def OnSet(self):
        self.control.checkSetting()

    # 置顶
    def OnTop(self):
        if self.IS_TOP:
            self.setWindowFlags(Qt.Widget | Qt.FramelessWindowHint)
            self.IS_TOP = False
            self.menuSelector_8.setIcon(QIcon(__icon_dir__ + '/untopping.png'))
        else:
            self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
            self.IS_TOP = True
            self.menuSelector_8.setIcon(QIcon(__icon_dir__ + '/topping.png'))
        self.show()

    # 退出并保存文件
    def OnExit(self):
        reply = QMessageBox.question(self, 'Warning', '确认退出？', QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            # 这里保存json文件
            with open(__config_dir__, 'w') as fp:
                json.dump(self.control.config , fp)
            print('退出程序')
            self.close()
        else:
            pass

    # 改变显示模式
    def chanShowMode(self, code):
        if code == 0:
            self.regTextBox.show()
            self.tranTextBox.show()
            self.menuSelector_6.setIcon(QIcon(__icon_dir__ + '/up_down.png'))
        elif code == 1:
            self.regTextBox.show()
            self.tranTextBox.hide()
            self.menuSelector_6.setIcon(QIcon(__icon_dir__ + '/up.png'))
        else: 
            self.regTextBox.hide()
            self.tranTextBox.show()
            self.menuSelector_6.setIcon(QIcon(__icon_dir__ + '/down.png'))

    # 定时截图控制函数
    def timingReg(self):
        base = self.control.config['READ_SPAN'] # 基础时间为1s
        self.th.chanSpan(base)
        if self.IS_AUTO:
            self.th.start()
        else:
            self.th.shotdown()

    # 重写方法实现窗口拖拽
    def OnPressEvent(self):
        pos = QCursor.pos()
        self.IS_MOVING = True
        self.m_Position = pos-self.pos()    # 获取鼠标相对窗口的位置
    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.IS_MOVING:
            self.move(QMouseEvent.globalPos()-self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()
    def mouseReleaseEvent(self, QMouseEvent):
        self.IS_MOVING=False

# 重写定时器实现子线程调用定时截图的功能
class CycleThread(QThread):
    timing = pyqtSignal(int)
    isAuto = True

    def __init__(self):
        super().__init__()

    def run(self):
        i = 0
        self.isAuto = True
        while self.isAuto:
            self.timing.emit(i)
            self.sleep(self.span)
        return

    def shotdown(self):
        self.isAuto = False

    def chanSpan(self, span):
        self.span = span
